#include <iostream>
#include <sys/types.h>        
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
using namespace std;

class Udp_Client
{

public:

    Udp_Client(int port, string ip)
        :_sockfd(-1)
        ,_server_port(port)
        ,_server_ip(ip)
    {}

    ~Udp_Client()
    {
        if(_sockfd > 0)
            close(_sockfd);
    }

    bool InitClient()
	{
		//创建套接字
		_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
		if (_sockfd < 0)
        {
			std::cerr << "socket create error" << std::endl;
			return false;
		}
		return true;
	}

    void Start()
    {
        string msg;
        struct sockaddr_in peer;
        memset(&peer, '\0', sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_server_port);
        peer.sin_addr.s_addr = inet_addr(_server_ip.c_str());

        for(;;)
        {
            cout << "Please Enter# " << endl;
            getline(cin, msg);
            //接受信息:
            if(sendto(_sockfd, msg.c_str(), msg.size(), 0, (sockaddr*)&peer, sizeof(peer)) < 0)
            {
                cerr << "sendto error!" << endl;
            }
            else
            {
                cout << "sento success!" << endl;
            }

            //发送消息:
        #define SIZE 128
            char buff[128];
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            ssize_t s = recvfrom(_sockfd, buff, sizeof(buff)-1, 0, (sockaddr*)&tmp, &len);
        }
    }

private:
    int _sockfd;
    int _server_port;
    string _server_ip;
};


int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        cerr << "Usage" << argv[1] << "ip and port!" << "argv[2]" << endl;
        return 1;
    }

    string server_ip = argv[1];
    int server_port = atoi(argv[2]);

    Udp_Client* clt = new Udp_Client(server_port, server_ip);
    clt->InitClient();
    clt->Start();
    return 0;
}